/*
* @(#) ProducerConsumer.java 2018年02月27日
*
* Copyright 2010 NetEase.com, Inc. All rights reserved.
*/
package com.leo.m1802.d27;

import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;

/**
 *
 * @author xuexiaolei
 * @version 2018年02月27日
 */
public class ProducerConsumer {
    private static BlockingQueue queue = new LinkedBlockingQueue();
    private static Random random = new Random();
    static class Producer implements Runnable{
        @Override public void run() {
            while (true){
                int i = random.nextInt(1000);
                queue.offer(i);
                System.out.println("Producer produce:" + i);
                try {
                    Thread.sleep(random.nextInt(1000));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    static class Consumer implements Runnable{
        @Override public void run() {
            while (true){
                Object poll = queue.poll();
                System.out.println("Consumer consume:" + poll);
                try {
                    Thread.sleep(random.nextInt(1000));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        ExecutorService exec = Executors.newFixedThreadPool(4);
        exec.submit(new Producer());
        exec.submit(new Producer());
        exec.submit(new Producer());
        exec.submit(new Consumer());
    }
}
